<template>
    <div class="content admin-list">
        <div class="search-content">
            <el-form ref="searchForm" :inline="true" :model="searchObj">
                <el-form-item label="用户名：" prop="admin_name">
                    <el-input
                        v-model="searchObj.admin_name"
                        placeholder="请输入用户名"
                        class="input w200"
                        clearable
                    ></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search">搜索</el-button>
                    <el-button type="primary" @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="agentList search-list" style="width:100%;">
            <el-table
                :data="aList"
                border
                style="width: 100%"
                ref="table"
                :height="oHeight"
                :header-cell-style="{'text-align':'center'}"
                :cell-style="{'text-align':'center'}"
            >
                <el-table-column fixed prop="admin_id" label="ID" key="admin_id" width="80"></el-table-column>
                <el-table-column
                    prop="admin_name"
                    label="用户名"
                    key="admin_name"
                    :show-overflow-tooltip="true"
                    min-width="160"
                ></el-table-column>
                <el-table-column
                    prop="admin_login_time"
                    label="最近登录"
                    key="admin_login_time"
                    :show-overflow-tooltip="true"
                    min-width="260"
                ></el-table-column>
                <el-table-column
                    prop="admin_is_super"
                    label="是否超级管理员"
                    key="admin_is_super"
                    min-width="120"
                    :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column fixed="right" align="center" label="操作" key="operate" min-width="200">
                    <template slot-scope="scope">
                        <el-button
                            class="operateBtn"
                            type="text"
                            @click="editPermission(scope.row.admin_id)"
                        >编辑权限</el-button>
                        <el-button
                            class="operateBtn"
                            type="text"
                            @click="edit(scope.row.admin_id, scope.row.admin_name)"
                        >编辑</el-button>
                        <el-button
                            class="operateBtn"
                            type="text"
                            @click="deleter(scope.row.admin_id)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <pagination
                :arr="aList"
                :total="total"
                :currentPage="currentPage"
                :handleSizeChange="handleSizeChange"
                :handleCurrentChange="handleCurrentChange"
            ></pagination>
            <!-- 编辑管理员权限 -->
            <el-drawer
                title="权限编辑"
                :visible.sync="drawer"
                :before-close="handleClose"
                size="86%"
                :append-to-body="true"
            >
                <div class="admin_list_edit_content">
                    <div>
                        <!-- <div
                            class="admin_list_check"
                            v-for="(item, index) in permissionList"
                            :key="item.menu_id"
                        >
                            
                            <el-checkbox
                                v-model="item.is_choose"
                                @change="handleCheckAllChange('first', index)"
                            >{{item.menu_name}}</el-checkbox>
                            <div style="margin: 15px 0;"></div>

                            <div
                                class="admin_list_check"
                                v-for="(items, indexs) in item.child"
                                :key="items.menu_id"
                            >
                                
                                <div v-if="!items.child">
                                    <el-checkbox
                                        v-model="items.is_choose"
                                        @change="handleCheckAllChange('second', index, indexs)"
                                    >{{items.menu_name}}</el-checkbox>
                                </div>
                                <div v-else>
                                    <el-checkbox
                                        v-model="items.is_choose"
                                        @change="handleCheckAllChange('third', index, indexs)"
                                    >{{items.menu_name}}</el-checkbox>
                                    <div style="margin: 15px 0;"></div>
                                    
                                    <div class="admin_list_check">
                                        <el-checkbox-group
                                            v-model="items.chooseList"
                                            @change="handleCheckAllChange('fouth', index, indexs)"
                                        >
                                            <el-checkbox
                                                v-for="itemes in items.child"
                                                :label="itemes.menu_id"
                                                :key="itemes.menu_id"
                                            >{{itemes.menu_name}}</el-checkbox>
                                        </el-checkbox-group>
                                    </div>
                                </div>
                                <div style="margin: 15px 0;"></div>
                            </div>
                        </div> -->
                        <el-tree
                            :data="permissionList"
                            show-checkbox
							check-strictly
                            default-expand-all
                            node-key="menu_id"
                            ref="tree"
                            highlight-current
                            :default-checked-keys="checkedKeys"
                            @check-change="checkChange"
                            :props="defaultProps"
                            
                        ></el-tree>
                    </div>
                    <div class="admin_list_check">
                        <el-button @click="handleClose">取 消</el-button>
                        <el-button type="primary" @click="editAdminPermission">确 定</el-button>
                        <div style="margin: 15px 0;"></div>
                    </div>
                </div>
            </el-drawer>
        </div>
        <!--编辑管理员-->
        <el-dialog title="编辑" :before-close="resectForm" :visible.sync="dialogFormVisible" class="admin-control-edit">
            <el-form :model="form" label-position="left" :rules="rules" ref="ruleForm">
                <el-form-item label="用户名" :label-width="formLabelWidth" prop="admin_name">
                    <el-input v-model.trim="form.admin_name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" :label-width="formLabelWidth" prop="admin_password">
                    <el-input v-model.trim="form.admin_password" autocomplete="new-password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" :label-width="formLabelWidth" prop="again_password">
                    <el-input v-model.trim="form.again_password" autocomplete="new-password" type="password"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="resectForm">取 消</el-button>
                <el-button type="primary" @click="editAdmin">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import pagination from "@/components/pagination/pagination.vue";
import { resize } from "@/common/js/height.js";
export default {
    name: "admin-list",
    data() {
        var validatePass2 = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请再次输入密码"));
            } else if (value !== this.form.admin_password) {
                callback(new Error("两次输入密码不一致!"));
            } else {
                callback();
            }
        };
          var validatePassWord = (rule, value, callback) => {
              let reg= /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$/;
            if (value === "") {
                callback(new Error("请输入密码"));
            } else if(!reg.test(value)){
                callback(new Error("包含数字、大小写字母、特殊符号，长度8位以上"));
            } else {
                callback();
            }
        };
        
        return {
            defaultProps: {
                children: 'child',
                label: 'menu_name'
            },
            checkedKeys: [],
            aList: [],
            oHeight: 800,
            total: 1,
            currentPage: 1,
            setCheckedKeys:[],
            // searchContent: {
            //   //该变量一直在变，用来定义默认搜索内容
            //   admin_name: ""
            // },
            searchObj: {
                //该变量定义查询传参
                pageSize: 10,
                page: 1,
                admin_name: ""
            },
            drawer: false, //侧边窗口控制弹出
            permissionList: [], //权限列表
            form: {
                //添加管理员表单
                admin_name: "",
                admin_password: "",
                admin_id: "",
                again_password: ""
            },
            dialogFormVisible: false,
            formLabelWidth: "80px",
            rules: {
                admin_name: {
                    required: true,
                    message: "请填写用户名",
                    trigger: "blur"
                },
                admin_password: {
                    required: true,
                    validator: validatePassWord,
                    trigger: "blur"
                },
                again_password: {
                    required: true,
                    validator: validatePass2,
                    trigger: "blur"
                }
            },
            // 编辑权限传的参数
            permissonOp: {
                admin_id: "",
                menus: []
            },
            admin_id: "" //点击编辑时获取到的管理员id
        };
    },
    props: ["changed"], //父子组件传值---添加管理员
    watch: {
        changed(n, o) {
            this.searchObj.page = 1;
            this.currentPage = 1;
            this.searchObj.admin_name = "";
            this.getList();
        }
    },
    components: {
        pagination
    },
    methods: {
        checkChange(data, checked, child) {
          let thisNode = this.$refs.tree.getNode(data.menu_id) // 获取当前节点
            const keys = this.$refs.tree.getCheckedKeys() // 获取已勾选节点的key值
            if (thisNode.checked) { // 当前节点若被选中
                for (let i = thisNode.level; i > 1; i--) { // 判断是否有父级节点
                if (!thisNode.parent.checked) { // 父级节点未被选中，则将父节点替换成当前节点，往上继续查询，并将此节点key存入keys数组
                    thisNode = thisNode.parent
                    keys.push(thisNode.data.menu_id)
                }
                }
            }else{//当前节点没有被选中
                 if(data.child){
                    data.child.forEach(ele=>{
                        var index = keys.indexOf(ele.menu_id); 
                        if (index > -1) { 
                        keys.splice(index, 1); 
                        } 
                    })
                }
            }
         this.$refs.tree.setCheckedKeys(keys) // 将所有keys数组的节点全选中
        this.setCheckedKeys=keys;
        
          /*  if (checked) {
                data.is_choose = 1;
            }else{
				data.is_choose = 1;
                if(data.child){
                  data.child.forEach(ele=>{
                    ele.is_choose = 0;
                })
                }
              
			}*/
        },
        setchoose(data,keys){
            if(keys.indexOf(data.menu_id)>-1){
                console.log(data.menu_name)
                data.is_choose=1;
            }else{
                  data.is_choose=0;
                }
             if(data.child){
                 data.child.forEach(ele=>{
                      this.setchoose(ele,keys)
                 })
             }
        },
        // 获取列表
        getList() {
            var that = this;
            this.searchObj.curpage = that.currentPage;
            this.$http
                .post(
                    "/admin/auth/index.php?act=adminManage&op=adminList",
                    this.searchObj
                )
                .then(
                    res => {
                        if (res.code == 1) {
                            this.aList = res.data.list;
                            this.aList.map((value, index) => {
                                if (value.admin_is_super == 1) {
                                    value.admin_is_super = "是";
                                } else {
                                    value.admin_is_super = "否";
                                }
                            });
                            this.total = parseInt(res.data.totalCount);
                        } else {
                            this.$message.error("获取数据失败！");
                            // alert(res.msg);
                            this.aList = [];
                        }
                    },
                    err => {
                        this.$message.error("获取数据失败！");
                    }
                );
        },
        // 搜索
        search() {
            //1、获取搜索的内容
            this.currentPage = 1;
            this.searchObj.page = 1;
            //2、获取内容列表
            this.getList();
        },
        // 重置
        reset() {
            //1、清空搜索的内容
            this.searchObj.admin_name = "";
            this.searchObj.page = 1;
            this.currentPage = 1;
            //2、获取内容列表
            this.getList();
        },
        //每页数据
        handleCurrentChange: function (val) {
            this.searchObj.page = val;
            this.currentPage = val;
            /*请求数据*/
            this.getList();
        },
        //分组一页多少数据
        handleSizeChange(val) {
            this.currentPage = 1;
            this.searchObj.page = 1;
            this.searchObj.pageSize = val;
            /*请求数据*/
            this.getList();
        },
        // 编辑权限
        editPermission(id) {
            this.admin_id = id;
            this.$http
                .post("/admin/auth/index.php?act=adminManage&op=adminMenus", {
                    admin_id: id
                })
                .then(
                    res => {
                        if (res.code == 1) {
                            this.drawer = true;
                            // this.permissionList = res.data;
                            // console.log(this.permissionList);
                            /* res.data.map((value, index) => {
                                value.is_choose = value.is_choose ? true : false;
                                if (value.child) {
                                    value.child.map((val, ind) => {
                                        val.is_choose = val.is_choose ? true : false;
                                        if (val.child) {
                                            val.chooseList = [];
                                            val.child.map((v, i) => {
                                                v.is_choose = v.is_choose ? true : false;
                                                if (v.is_choose) {
                                                    val.chooseList.push(v.menu_id);
                                                }
                                            });
                                        }
                                    });
                                }
                            }); */
                            function chooseKeys(menuArr) {
                                var keyArr = [];
                                var chooseKeyFn = function (arr) {
                                    arr.map(item => {
                                        if (item.is_choose) {
											keyArr.push(item.menu_id)
										}
										if(item.child){
											chooseKeyFn(item.child)
										}
                                    })
								}
								chooseKeyFn(menuArr);
								return keyArr;
                            }
							this.checkedKeys = chooseKeys(res.data);
                            this.permissionList = Object.assign([], res.data);
                        } else {
                            this.$message({
                                showClose: true,
                                message: res.msg,
                                type: "error"
                            });
                        }
                    },
                    err => {
                        this.$message.error("获取数据失败！");
                    }
                );
        },
        // 权限编辑关闭
        handleClose(done) {
            this.$confirm("确认关闭？")
                .then(_ => {
                    this.drawer = false;
                    done();
                })
                .catch(_ => { });
        },
        // 全选反选
        handleCheckAllChange(type, index, indexes) {
            if (type == "first") {
                //第一级
                this.permissionList.map((value, indexs) => {
                    // 判断第一级是否选中
                    if (this.permissionList[index].is_choose) {
                        if (this.permissionList[index].child) {
                            this.permissionList[index].child.map((val, ind) => {
                                val.is_choose = true;
                                if (val.child) {
                                    val.child.map((v, i) => {
                                        v.is_choose = true;
                                        val.chooseList.push(v.menu_id);
                                    });
                                }
                            });
                        }
                    } else {
                        if (this.permissionList[index].child) {
                            this.permissionList[index].child.map((val, ind) => {
                                val.is_choose = false;
                                if (val.child) {
                                    val.child.map((v, i) => {
                                        v.is_choose = false;
                                        val.chooseList = [];
                                    });
                                }
                            });
                        }
                    }
                });
            } else if (type == "second") {
                //第二级
                this.permissionList.map((value, indexs) => {
                    // 判断第二级选中数量是否等于第一级child长度
                    let arr = [];
                    this.permissionList[index].child.map((val, ind) => {
                        if (val.is_choose) {
                            arr.push(val.menu_id);
                        }
                    });
                    if (arr.length == this.permissionList[index].child.length) {
                        this.permissionList[index].is_choose = true;
                    } else {
                        this.permissionList[index].is_choose = false;
                    }
                });
            } else if (type == "third") {
                //有第三极的情况
                this.permissionList.map((value, indexs) => {
                    // 判断第二级是否选中
                    if (this.permissionList[index].child[indexes].is_choose) {
                        if (this.permissionList[index].child[indexes].child) {
                            this.permissionList[index].child[indexes].chooseList = [];
                            this.permissionList[index].child[indexes].child.map(
                                (val, ind) => {
                                    this.permissionList[index].child[indexes].chooseList.push(
                                        val.menu_id
                                    );
                                    val.is_choose = true;
                                }
                            );
                        }
                    } else {
                        if (this.permissionList[index].child[indexes].child) {
                            this.permissionList[index].child[indexes].chooseList = [];
                            this.permissionList[index].child[indexes].child.map(
                                (val, ind) => {
                                    val.is_choose = false;
                                }
                            );
                        }
                    }
                    // 判断第二级选中数量是否等于第一级child长度
                    let arr = [];
                    this.permissionList[index].child.map((val, ind) => {
                        if (val.is_choose) {
                            arr.push(val.menu_id);
                        }
                    });
                    if (arr.length == this.permissionList[index].child.length) {
                        this.permissionList[index].is_choose = true;
                    } else {
                        this.permissionList[index].is_choose = false;
                    }
                });
            } else {
                //第三极
                this.permissionList.map((value, indexs) => {
                    if (
                        this.permissionList[index].child[indexes].chooseList.length ==
                        this.permissionList[index].child[indexes].child.length
                    ) {
                        this.permissionList[index].child[indexes].is_choose = true;
                    } else {
                        this.permissionList[index].child[indexes].is_choose = false;
                    }
                    let arr = [];
                    this.permissionList[index].child.map((val, ind) => {
                        if (val.is_choose) {
                            arr.push(val.menu_id);
                        }
                    });
                    // 全选反选
                    if (arr.length == this.permissionList[index].child.length) {
                        this.permissionList[index].is_choose = true;
                    } else {
                        this.permissionList[index].is_choose = false;
                    }
                    this.permissionList[index].child[indexes].child.map(v => {
                        v.is_choose = false;
                    });
                    // 处理数据
                    this.permissionList[index].child[indexes].chooseList.map(val => {
                        this.permissionList[index].child[indexes].child.map(v => {
                            if (val == v.menu_id) {
                                v.is_choose = true;
                            }
                        });
                    });
                });
            }
        },
        // 删除管理员
        deleter(id) {
            this.$confirm("确认删除？")
                .then(_ => {
                    this.$http
                        .post("/admin/auth/index.php?act=adminManage&op=delAdmin", {
                            admin_id: id
                        })
                        .then(
                            res => {
                                if (res.code == 1) {
                                    this.$message({
                                        showClose: true,
                                        message: res.msg,
                                        type: "success"
                                    });
                                    this.searchObj.page = 1;
                                    this.currentPage = 1;
                                    this.searchObj.admin_name = "";
                                    this.getList();
                                } else {
                                    this.$message({
                                        showClose: true,
                                        message: res.msg,
                                        type: "error"
                                    });
                                }
                            },
                            err => {
                                this.$message({
                                    showClose: true,
                                    message: res.msg,
                                    type: "error"
                                });
                            }
                        );
                    done();
                })
                .catch(_ => { });
        },
        resectForm(){
            this.$refs["ruleForm"].resetFields();
              this.dialogFormVisible = false;
        },
        // 点击编辑中的确定
        editAdmin() {
          
        
            this.$refs.ruleForm.validate(valid => {
                if (valid) {
                    this.$http
                        .post(
                            "/admin/auth/index.php?act=adminManage&op=addAdmin",
                            this.form
                        )
                        .then(
                            res => {
                                if (res.code == 1) {
                                    this.$message({
                                        showClose: true,
                                        message: res.msg,
                                        type: "success"
                                    });
                                    this.dialogFormVisible = false;
                                     
                                } else {
                                    this.$message({
                                        showClose: true,
                                        message: res.msg,
                                        type: "error"
                                    });
                                }
                            },
                            err => {
                                this.$message.error("获取数据失败！");
                            }
                        );
                } else {
                    return false;
                }
            });
        },
        // 点击编辑
        edit(id, name) {
            this.dialogFormVisible = true;
            this.form.admin_id = id;
            this.form.admin_name = name;
           
        },
        // 编辑权限确定
        editAdminPermission() {
            // debugger
             for(var i=0;i<this.permissionList.length;i++){
          // this.setchoose(this.permissionList[i],this.setCheckedKeys)
         }
       
                    let obj = {
						admin_id: this.admin_id,
						menus:this.setCheckedKeys.toString()
                    };
                   // obj=JSON.parse(JSON.stringify(obj))
                   // console.log(6666,obj)
            this.$confirm("确认修改？")
                .then(_ => {
                    const loading = this.$loading({
                        lock: true,
                        text: "Loading",
                        spinner: "el-icon-loading",
                        background: "rgba(255, 255, 255, 0.7)"
                    });
                  
                    // 深拷贝数组
                    this.$http
                        .post(
                            "/admin/auth/index.php?act=adminManage&op=editAdminMenus",
                            obj
                        )
                        .then(
                            res => {
                                loading.close();
                                this.drawer = false;
                                if (res.code == 1) {
                                    this.$message({
                                        showClose: true,
                                        message: res.msg,
                                        type: "success"
                                    });
                                } else {
                                    this.$message({
                                        showClose: true,
                                        message: res.msg,
                                        type: "error"
                                    });
                                }
                            },
                            err => {
                                this.$message.error("获取数据失败！");
                            }
                        );
                    done();
                })
                .catch(_ => { });
        }
    },
    mounted() {
        //页面刷新就执行
        localStorage.eachNum = "";
        this.getList();
        resize(this);
    },
    activated() {
        localStorage.eachNum = "";
        this.getList();
        resize(this);
        this.$nextTick(() => {
            this.$refs.table.doLayout(); //解决表格错位
        });
    }
};
</script>
<style scoped lang="scss">
.operateBtn {
    // margin-left: 0;
}
.admin-control-edit {
    .el-input {
        width: 60%;
    }
}
.admin_list_check {
    padding: 0 20px;
}
.admin_list_item {
    padding: 0 40px;
}
.admin_list_edit_content {
    display: flex;
    flex-direction: column;
    height: 100%;
    justify-content: space-between;
}
/deep/.el-drawer__body {
    overflow: auto;
}
</style>